# downloader/updater.py

import os
import requests
import json
from datetime import datetime, timedelta

CACHE_PATH = os.path.expanduser("~/.video-downloader/update_notes_cache.json")

def get_tool_version(tool_name):
    try:
        if tool_name == "yt-dlp":
            import yt_dlp
            return yt_dlp.__version__
        elif tool_name == "you-get":
            import you_get
            return you_get.__version__
    except Exception:
        return "未知"

def update_tool(tool_name):
    if tool_name == "yt-dlp":
        os.system("pip install --user yt-dlp --upgrade")
    elif tool_name == "you-get":
        os.system("pip install --user you-get --upgrade")
    return f"{tool_name} 已尝试更新，请重启应用"

def get_release_notes(tool_name):
    try:
        if tool_name == "yt-dlp":
            url = "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"
        elif tool_name == "you-get":
            url = "https://api.github.com/repos/soimort/you-get/releases/latest"
        response = requests.get(url, timeout=10)
        return response.json()["body"]
    except Exception as e:
        return f"获取失败: {e}"

def load_notes_cache():
    if not os.path.exists(CACHE_PATH):
        return {}
    with open(CACHE_PATH, "r", encoding="utf-8") as f:
        return json.load(f)

def is_cache_valid(tool_name, max_age_minutes=1440):
    cache = load_notes_cache()
    entry = cache.get(tool_name, {})
    timestamp = entry.get("timestamp")
    if not timestamp:
        return False
    cache_time = datetime.fromisoformat(timestamp)
    return (datetime.now() - cache_time).total_seconds() < (max_age_minutes * 60)

def refresh_cache_async(tool_name):
    if not is_cache_valid(tool_name):
        try:
            notes = get_release_notes(tool_name)
            save_notes_cache(tool_name, notes)
        except Exception as e:
            print(f"缓存刷新失败: {e}")

def save_notes_cache(tool_name, notes):
    cache = load_notes_cache()
    cache[tool_name] = {
        "notes": notes,
        "timestamp": datetime.now().isoformat()
    }
    with open(CACHE_PATH, "w", encoding="utf-8") as f:
        json.dump(cache, f, indent=2)

def cleanup_old_versions(tool_name, new_version):
    pass  # 可扩展为实际版本清理逻辑

def cleanup_download_cache(tool_name):
    pass  # 可扩展为实际缓存清理逻辑